package com.atguigu.signature;

import com.atguigu.rsa.RSAdemo;
import com.sun.org.apache.xml.internal.security.utils.Base64;

import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;

/**
 * SignatureDemo
 *
 * @Author: 马伟奇
 * @CreateTime: 2021-02-27
 * @Description:
 */
public class SignatureDemo {
    public static void main(String[] args) throws Exception{
        // 定义原文
        String input = "abc";
        // 数字签名 = 非对称加密算法 + 数字摘要算法
        PublicKey publicKey = RSAdemo.getPublicKey("a.pub","RSA");
        PrivateKey privateKey = RSAdemo.getPrivateKey("a.pri","RSA");
        String result = getSignature(input, "sha256withrsa", privateKey);
        System.out.println(result);

        boolean b = verifySignature(input, "sha256withrsa", publicKey, result);
        System.out.println(b);
    }

    private static boolean verifySignature(String input,
                                           String sha256withrsa,
                                           PublicKey publicKey,
                                           String result) throws Exception{

        Signature signature = Signature.getInstance(sha256withrsa);

        signature.initVerify(publicKey);

        signature.update(input.getBytes());

        return signature.verify(Base64.decode(result));
    }

    /**
     *
     * @param input 表示原文
     * @param sha256withrsa 表示算法
     * @param privateKey 表示私钥key
     * @return
     */
    private static String getSignature(String input, String sha256withrsa, PrivateKey privateKey) throws Exception{
        // 获取数字签名对象
        Signature signature = Signature.getInstance(sha256withrsa);
        // 初始化签名
        signature.initSign(privateKey);
        // 传入原文
        signature.update(input.getBytes());
        // 进行签名
        byte[] sign = signature.sign();
        return Base64.encode(sign);
    }
}